package com.greensecurity.sim.controller;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.greensecurity.sim.entity.GreenLandPhoto;
import com.greensecurity.sim.entity.PhotoDistinguish;
import com.greensecurity.sim.entity.User;
import com.greensecurity.sim.repository.GreenLandPhotoRepostitory;
import com.greensecurity.sim.service.PhotoDistinguishService;
import com.greensecurity.sim.service.UserService;
import com.greensecurity.sim.util.BatPhotoDistinguish;
import com.greensecurity.sim.util.IsWindowOrLinuxUtils;
import com.greensecurity.sim.util.SaveImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/photo")
@Slf4j
@CrossOrigin(origins = "*")
@Api(description = "图片识别")
public class PhotoController {
    @Resource
    private UserService userService;
    @Resource
    private PhotoDistinguishService photoDistinguishService;
    @Resource
    private GreenLandPhotoRepostitory greenLandPhotoRepostitory;

    @ApiOperation(value = "上传图像识别图片")
    @ResponseBody
    @PostMapping("/upImage/{name}")
    public String upImage(@PathVariable String name, @RequestBody String baseImage){
        try {
            //将 data:image/jpeg;base64, 去掉，不然图片无法保存 23
//            baseCAD=baseCAD.split("base64,")[1];
//            baseImage.split(String.valueOf(23));
            JSONObject BaseToJson=JSONObject.parseObject(baseImage);
            User user=userService.findByPhone(BaseToJson.getString("userPhone"));
            if (user.getPhotoDistinguishNum() == 0){
                throw new RuntimeException("图像识别次数已用用尽，请联系管理员");
            }
            baseImage=BaseToJson.getString("base64");
            String cadSavePath= IsWindowOrLinuxUtils.getPhotoDistinguishPath();
            cadSavePath+="/"+name;
            log.info("图片保存路径：{}",cadSavePath);
            SaveImageUtil.saveImage(baseImage,cadSavePath);
            log.info("图片开始解析.................");
            String getPhotoDistinguish =  getPhotoDistinguish(cadSavePath);
            log.info(getPhotoDistinguish);
            user.setPhotoDistinguishNum(user.getPhotoDistinguishNum()-1);
            userService.save(user);
            PhotoDistinguish photoDistinguish = new PhotoDistinguish();
            photoDistinguish.setPhotoUrl(IsWindowOrLinuxUtils.savePhotoDisUrl()+"/"+name);
            photoDistinguish.setDistinguishResult(getPhotoDistinguish.toString());
            photoDistinguish.setUser(user);
//            log.info(photoDistinguish.toString());
            photoDistinguishService.save(photoDistinguish);
            return getPhotoDistinguish;
        } catch (Exception e) {
            throw new RuntimeException("保存失败:"+e.getMessage());
        }
    }

    @ApiOperation(value = "获取图片识别结果")
    @GetMapping("/getPhotoDistinguish/{imgUrl}")
    public String getPhotoDistinguish(@PathVariable String imgUrl) {
        return BatPhotoDistinguish.animal(imgUrl);
    }

    @ApiOperation(value = "上传用户头像图片")
    @ResponseBody
    @PostMapping("/upUserImage/{name}")
    public String upUserImage(@PathVariable String name, @RequestBody String userAndImage){
        try {
//            获取图片保存路径
            String cadSavePath= IsWindowOrLinuxUtils.getUserImageSavePath();
            cadSavePath+="/"+name;
            log.info("图片保存路径：{}",cadSavePath);
//            将接受的数据转为json格式，方便拿取
            JSONObject jsonObject = JSON.parseObject(userAndImage);
            String base64Url = jsonObject.get("base64").toString();
            User upUser = JSONObject.parseObject(jsonObject.get("user").toString(),User.class) ;
//            更改数据库User的照片保存路径
            User upUser1 = userService.findByPhone(upUser.getPhone());
            upUser1.setUserPhotoUrl(IsWindowOrLinuxUtils.savaUserPhotoUrl()+"/"+name);
            userService.save(upUser1);
            SaveImageUtil.saveImage(base64Url,cadSavePath);
            log.info("图片开始解析.................");
            return "图片保存成功："+IsWindowOrLinuxUtils.getPhotoUrl()+IsWindowOrLinuxUtils.savaUserPhotoUrl()+"/"+name;
        } catch (Exception e) {
//            log.error("保存失败:",e);
            throw new RuntimeException("保存失败:"+e.getMessage());
        }
    }

    @ApiOperation(value = "上传绿地信息图片")
    @ResponseBody
    @PostMapping("/upGreenLandImage/{name}")
    public String upGreenLandImage(@PathVariable String name, @RequestBody String base64){
        try {
            //将 data:image/jpeg;base64, 去掉，不然图片无法保存 23
//            baseCAD=baseCAD.split("base64,")[1];
//            base64= base64.split("data:image/jpeg;base64,")[0];
//            获取图片保存路径
            String cadSavePath= IsWindowOrLinuxUtils.getGreenLandImageSavePath();
            cadSavePath+="/"+name;
            log.info("图片保存路径：{}",cadSavePath);
            SaveImageUtil.saveImage(base64,cadSavePath);
            log.info("图片开始解析.................");
            return "图片保存成功："+IsWindowOrLinuxUtils.getPhotoUrl()+IsWindowOrLinuxUtils.saveGreenLandPhotoUrl()+"/"+name;
        } catch (Exception e) {
            log.error("保存失败:",e);
            return "保存失败";
        }
    }
    @ApiOperation(value = "web端编辑用户信息的Element UI upload组件上传图片接口")
    @ResponseBody
    @PostMapping(value = "/upload/{phone}")
    // 此处的@RequestParam中的file名应与前端upload组件中的name的值保持一致
    public String upload(@RequestParam("file") MultipartFile multipartFile,@PathVariable String phone) {
        // replaceAll 用来替换windows中的\\ 为 /
        String savaPath = "/"+phone+"-title.jpg";
        String filePath = IsWindowOrLinuxUtils.getUserImageSavePath()+savaPath;
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 文件存储
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        User user= userService.findByPhone(phone);
        user.setUserPhotoUrl(IsWindowOrLinuxUtils.savaUserPhotoUrl()+savaPath);
        userService.save(user);
        return IsWindowOrLinuxUtils.getPhotoUrl()+user.getUserPhotoUrl();
    }
    @ApiOperation(value = "web端 新增 用户信息的Element UI upload组件上传图片接口")
    @ResponseBody
    @PostMapping(value = "/uploadAdd")
    // 此处的@RequestParam中的file名应与前端upload组件中的name的值保持一致
    public List<String> uploadAdd(@RequestParam("file") MultipartFile multipartFile) {
        // replaceAll 用来替换windows中的\\ 为 /
        String savaPath = "/addUser-title.jpg";
        String filePath = IsWindowOrLinuxUtils.getUserImageSavePath()+savaPath;
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 文件存储
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> re = new ArrayList<>();
        re.add(IsWindowOrLinuxUtils.getPhotoUrl()+IsWindowOrLinuxUtils.savaUserPhotoUrl()+savaPath);
        re.add(IsWindowOrLinuxUtils.savaUserPhotoUrl()+savaPath);
        return re;
    }

    @ApiOperation(value = "Web Element UI 上传绿地信息图片")
    @ResponseBody
    @PostMapping("/saveGreenLandPhoto/{id}")
    public String saveGreenLandPhoto(@RequestParam("file") MultipartFile multipartFile,@PathVariable Long id){
        Optional<GreenLandPhoto> greenLandPhoto =greenLandPhotoRepostitory.findById(id);
        GreenLandPhoto greenLandPhoto1= greenLandPhoto.get();
        String filePath = IsWindowOrLinuxUtils.getSaveWinOrLinux()+greenLandPhoto1.getPhotoUrl();
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                file.delete();
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 文件存储
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return IsWindowOrLinuxUtils.getPhotoUrl()+greenLandPhoto1.getPhotoUrl();
    }
}